/*******************************************************************************
 * 
 ******************************************************************************/
var addUserWin;
var updateUserWin;
var searchUserWin;
var userAddForm;
var userUpdateForm;
var userGrid;
var u_l_store;
var u_s_store;
var u_cm;
var u_sel_ids = [];
var u_sel_name;

var addRoleWin;
var updateRoleWin;
var roleAddForm;
var roleUpdateForm;
var roleGrid;
var ro_l_store;
var ro_s_store;
var ro_cm;
var ro_sel_ids = [];
var ro_sel_name;

var addResourceWin;
var updateResourceWin;
var resourceAddForm;
var resourceUpdateForm;
var resourceGrid;
var re_l_store;
var re_s_store;
var re_cm;
var re_sel_ids = [];
var re_sel_name;

var pageSize = 5;

Ext.onReady(function() {
	/*
	 * Ext.QuickTips.init();
	 * 
	 * Ext.form.Field.prototype.msgTarget = "side";
	 * 
	 * Ext.BLANK_IMAGE_URL =
	 * "http://localhost/extjstest/resources/images/default/s.gif";
	 */

	Ext.apply(Ext.form.VTypes, {
				"tel" : function(_v) {

					if (/^\d+$/.test(_v)) {
						return true;
					}

					return false;

				},
				"telText" : "该输入项必须是电话格式,格式如:150...",
				"ageMask" : /[0-9]/i
			});
	Ext.apply(Ext.form.VTypes, {
				password : function(val, field) {// val指这里的文本框值，field指这个文本框组件，大家要明白这个意思
					if (field.confirmTo) {// confirmTo是我们自定义的配置参数，一般用来保存另外的组件的id值
						var pwd = Ext.get(field.confirmTo);// 取得confirmTo的那个id的值
						return (val == pwd.getValue());
					}
					return true;
				},
				"passwordText" : "两次密码不一致!"

			});

	// var _panel = new PersonListGridPanel();
	/** *************************************************** */

	TopicRecord = Ext.data.Record.create([{
				name : 'id',
				mapping : 'user.id'
			}, {
				name : 'name',
				mapping : 'user.name'
			}, {
				name : 'password',
				mapping : 'user.password'
			}, {
				name : 'sex',
				mapping : 'user.sex'
			}, {
				name : 'tel',
				mapping : 'user.tel'
			}, {
				name : 'disable',
				mapping : 'user.disable'
			}]);

	u_cm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(),
			new Ext.grid.CheckboxSelectionModel(), {

				header : "编号",

				align : "center",

				dataIndex : "id"

			}, {

				header : "姓名",

				align : "center",

				dataIndex : "name"

			}, {

				header : "性别",

				dataIndex : "sex",

				align : "center"

			}, {

				header : "电话",

				dataIndex : "tel",

				align : "center"

			}, {

				header : "状态",

				dataIndex : "disable",

				align : "center"

			}]);

	ro_cm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(),
			new Ext.grid.CheckboxSelectionModel(), {

				header : "编号",

				align : "center",

				dataIndex : "id"

			}, {

				header : "名称",

				align : "center",

				dataIndex : "name"

			}, {

				header : "描述",

				dataIndex : "discription",

				align : "center"

			}]);		
			
	u_l_store = new Ext.data.Store({
				proxy : new Ext.data.HttpProxy({
							url : "userAction!list.action"
						}),
				reader : new Ext.data.JsonReader({
							totalProperty : 'totalProperty',
							root : 'user_list',
							successProperty : 'SUCCESS',
							fields : [{
										name : 'id',
										mapping : 'id'
									}, {
										name : 'name',
										mapping : 'name'
									}, {
										name : 'sex',
										mapping : 'sex'
									}, {
										name : 'tel',
										mapping : 'tel'
									}, {
										name : 'disable',
										mapping : 'disable'
									}]
						}),

				sortInfo : {
					field : 'id',
					direction : 'ASC'
				}

			});

	ro_l_store = new Ext.data.Store({
				proxy : new Ext.data.HttpProxy({
							url : "roleAction!list.action"
						}),
				reader : new Ext.data.JsonReader({
							totalProperty : 'totalProperty',
							root : 'role_list',
							successProperty : 'SUCCESS',
							fields : [{
										name : 'id',
										mapping : 'id'
									}, {
										name : 'name',
										mapping : 'name'
									}, {
										name : 'discription',
										mapping : 'discription'
									}]
						}),

				sortInfo : {
					field : 'id',
					direction : 'ASC'
				}

			});

	ro_s_store = new Ext.data.Store({
				proxy : new Ext.data.HttpProxy({
							url : "userAction!searchRoles.action"
						}),
				reader : new Ext.data.JsonReader({
							totalProperty : 'totalProperty',
							root : 'role_list',
							successProperty : 'SUCCESS',
							fields : [{
										name : 'id',
										mapping : 'id'
									}, {
										name : 'name',
										mapping : 'name'
									}, {
										name : 'discription',
										mapping : 'discription'
									}]
						}),

				sortInfo : {
					field : 'id',
					direction : 'ASC'
				}

			});		
			
	userAddForm = new Ext.form.FormPanel({
				url : "userAction!add.action",
				// url : "UserAction!update.action",
				method : 'post',
				defaultType : "textfield",
				labelWidth : 55,
				defaults : {
					anchor : "92%"
				},
				baseCls : "x-plain",
				items : [{
							fieldLabel : "姓名",
							name : "user.name",
							allowBlank : false
						}, {
							xtype : "combo",
							hiddenName : "user.sex",
							fieldLabel : "性别",
							mode : "local",
							displayField : "sex",
							readOnly : true,
							triggerAction : "all",
							value : "男",
							disabled : false,
							editable : false,
							store : new Ext.data.SimpleStore({
										fields : ["sex"],
										data : [["男"],

												["女"]]
									})
						}, {
							fieldLabel : "密码",
							id : "pass1",
							name : "user.password",
							inputType : "password",
							allowBlank : false
						}, {
							fieldLabel : "确认密码",
							id : "pass2",
							vtype : "password",
							confirmTo : "pass1",
							name : "pw",
							inputType : "password",
							allowBlank : false
						}, {
							fieldLabel : "电话",
							vtype : "tel",
							name : "user.tel",
							allowBlank : false
						}, {
							fieldLabel : "状态",
							xtype : "combo",
							hiddenName : "user.disable",
							allowBlank : false,
							value : "1",
							store : new Ext.data.SimpleStore({
										fields : ['index', 'disc'],
										data : [[1, '有效'], [0, '无效']]
									}),
							valueField : 'index',
							displayField : 'disc',
							mode : 'local',
							triggerAction : 'all',
							editable : false
						}]
			});

	userUpdateForm = new Ext.form.FormPanel({
				url : "userAction!update.action",
				method : 'post',
				defaultType : "textfield",
				labelWidth : 55,
				defaults : {
					anchor : "92%"
				},
				baseCls : "x-plain",
				items : [{
							xtype : "hidden",
							name : "user.id"
						}, {
							fieldLabel : "姓名",
							name : "user.name",
							allowBlank : false
						}, {
							xtype : "combo",
							hiddenName : "user.sex",
							fieldLabel : "性别",
							mode : "local",
							displayField : "sex",
							readOnly : true,
							triggerAction : "all",
							value : "男",
							disabled : false,
							editable : false,
							store : new Ext.data.SimpleStore({
										fields : ["sex"],
										data : [["男"],

												["女"]]
									})
						}, {
							fieldLabel : "电话",
							vtype : "tel",
							name : "user.tel",
							allowBlank : false
						}, {
							fieldLabel : "状态",
							xtype : "combo",
							hiddenName : "user.disable",
							allowBlank : false,
							value : "有效",
							store : new Ext.data.SimpleStore({
										fields : ['index', 'disc'],
										data : [[1, '有效'], [0, '无效']]
									}),
							valueField : 'index',
							displayField : 'disc',
							mode : 'local',
							triggerAction : 'all',
							editable : false
						}]

			});

	addUserWin = new Ext.Window({
		layout : 'fit',
		buttonAlign : 'center',
		width : 330,
		height : 300,
		closeAction : 'hide',
		modal : true,
		plain : true,
		buttons : [{
					text : '保存',
					handler : function() {
						// alert(userAddForm.getForm().url);
						if (userAddForm.getForm().isValid()) {
							userAddForm.getForm().submit({

										success : function(form, action) {
											userAddForm.getForm().reset();
											addUserWin.hide();
											userGrid.getStore().removeAll();
											userGrid.getStore().load({
														params : {
															start : 0,
															limit : pageSize
														}
													});
										},
										failure : function(form, action) {
											Ext.Msg.alert('提示', '原因如下：' + "df");
										},

										waitMsg : '保存数据...'
									});
						}
					}
				}, {
					text : '清空',
					handler : function() {
						userAddForm.getForm().reset();
					}
				}, {
					text : '关闭',
					handler : function() {
						userAddForm.getForm().reset();
						addUserWin.hide();
					}
				}],
		items : [userAddForm]
	});

	updateUserWin = new Ext.Window({
				layout : 'fit',
				buttonAlign : 'center',
				width : 330,
				height : 300,
				closeAction : 'hide',
				modal : true,
				plain : true,
				buttons : [{
							text : '保存',
							handler : function() {
								if (userUpdateForm.getForm().isValid()) {
									userUpdateForm.getForm().submit({
												success : function(form, action) {
													userUpdateForm.getForm()
															.reset();
													updateUserWin.hide();
													userGrid.getStore()
															.removeAll();
													userGrid.getStore().load({
																params : {
																	start : 0,
																	limit : pageSize
																}
															});
												},
												waitMsg : '保存数据...'
											});
								}
							}
						}, {
							text : '取消',
							handler : function() {
								userUpdateForm.getForm().reset();
								updateUserWin.hide();
							}
						}],
				items : [userUpdateForm]
			});

	searchUserWin = new Ext.Window({
				title : '查找人员',
				layout : 'form',
				width : 300,
				height : 180,
				closeAction : 'hide',
				buttonAlign : 'center',
				labelWidth : 55,
				modal : true,
				plain : true,

				buttons : [{
					text : '查找',
					handler : function() {
						userGrid.getStore().removeAll();
						userGrid.reconfigure(u_s_store, u_cm);
						//alert("name:" + Ext.getCmp("searchName").getValue());
						u_s_store.load({
									params : {
										start : 0,
										limit : pageSize,
										"user.id" : Ext.getCmp("searchId")
												.getValue(),
										"user.name" : Ext.getCmp("searchName")
												.getValue()
									}
								});
						searchUserWin.hide();
						Ext.getCmp("searchId").setValue("");
						Ext.getCmp("searchName").setValue("");
					}

				}, {
					text : '取消',
					handler : function() {
						Ext.getCmp("searchId").setValue("");
						Ext.getCmp("searchName").setValue("");
						searchUserWin.hide();
					}
				}],
				items : [{
							fieldLabel : '编号',
							width : 200,
							id : 'searchId',
							name : 'searchId',
							// allowBlank : false,
							xtype : 'textfield'

						}, {

							fieldLabel : '名称',
							id : 'searchName',
							name : 'searchName',
							width : 200,
							// allowBlank : false,
							xtype : 'textfield'

						}]

			});

	u_s_store = new Ext.data.Store({
				proxy : new Ext.data.HttpProxy({
							url : "userAction!search.action"
						}),
				reader : new Ext.data.JsonReader({
							totalProperty : 'totalProperty',
							root : 'user_list',
							successProperty : 'SUCCESS',
							fields : [{
										name : 'id',
										mapping : 'id'
									}, {
										name : 'name',
										mapping : 'name'
									}, {
										name : 'sex',
										mapping : 'sex'
									}, {
										name : 'tel',
										mapping : 'tel'
									}, {
										name : 'disable',
										mapping : 'disable'
									}]
						}),

				sortInfo : {
					field : 'id',
					direction : 'ASC'
				}

			});

	userGrid = new Ext.grid.GridPanel({
		renderTo : 'gridPanel',
		store : u_l_store,
		cm : u_cm,
		autoHeight : true,
		title : '人员信息',
		frame : true,
		stripeRows : true,
		tbar : [{
					text : "添加人员",
					handler : function() {
						addUserWin.show();
					},
					scope : this
				}, "-", {
					text : "修改人员",
					handler : function() {
						var sm = userGrid.getSelectionModel();
						if (sm.hasSelection()) {
							updateUserWin.show();
							try {
								var data = userGrid.getSelectionModel()
										.getSelected();
								var myNewRecord = new TopicRecord({
											'user.id' : data.get("id"),
											'user.name' : data.get("name"),
											'user.sex' : data.get("sex"),
											'user.tel' : data.get("tel"),
											'user.disable' : data
													.get("disable"),
											'user.password' : data
													.get("password")
										});
								userUpdateForm.getForm()
										.loadRecord(myNewRecord);

							} catch (_err) {
								Ext.Msg.alert("系统提示", _err.description);
								updateUserWin.hide();
							}
						} else {
							Ext.Msg.alert('信息', "请选中一行！");
						}
					},
					scope : this
				}, "-", {
					text : "删除人员",
					handler : function() {
						var sm = userGrid.getSelectionModel();
						if (sm.hasSelection()) {
							Ext.Msg.confirm('信息', '确定要删除?', function(btn) {
								if (btn == 'yes') {
									var _sr = userGrid.getSelectionModel()
											.getSelections();
											u_sel_ids = [];
									for (var i = 0; i < _sr.length; i++) {
										u_sel_ids[i] = _sr[i].get("id");
									}
									Ext.Ajax.request({
												url : "userAction!delete.action",
												params : {
													selectedList : u_sel_ids
												}
											});
									for (var i = 0; i < _sr.length; i++) {
										// alert(_sr[i].get("id"));
										userGrid.getStore().remove(userGrid
												.getStore().getAt(_sr[i]
														.get("id")));
									}
									userGrid.getStore().reload({
												params : {
													start : 0,
													limit : pageSize
												}
											});
								} else {
									Ext.Msg.alert('信息', "请选中一行！");
								}
							});
						} else {
							Ext.Msg.alert('信息', "请选中纪录！");
						}
					},
					scope : this
				}, "-", {
					text : "查找人员",
					handler : function() {
						searchUserWin.show();
					},
					scope : this
				}, "-", {
					text : "分配角色",
					handler : function() {
						var sm = userGrid.getSelectionModel();
						if (sm.hasSelection()) {
							var record = sm.getSelected();
							current_selected_id = record.get("id");
							current_selected_name = record.get("name");
							alert(':' + current_selected_name);
							userGrid.hide();
							roleGrid.setTitle("人员"+current_selected_name+"的角色列表");
							roleGrid.show();
							ro_s_store.load({
										params : {
											start : 0,
											limit : pageSize,
											current_selected_id : current_selected_id
										}
									});
						} else {
							Ext.Msg.alert('信息', "请选中一行！");
						}
					},
					scope : this
				}],
		enableColumnMove : false,
		selModel : new Ext.grid.CheckboxSelectionModel(),
		bbar : new Ext.PagingToolbar({
					pageSize : pageSize,
					store : u_l_store
				})
	});

	roleGrid = new Ext.grid.GridPanel({
		renderTo : 'gridPanel',
		title : "角色列表",
		store : ro_s_store,
		cm : ro_cm,
		autoHeight : true,
		frame : true,
		stripeRows : true,
		tbar : [{
					text : "添加角色",
					handler : function() {
						addRolesWin.show();
						addRolesWin.center();
						addRolesWin.show();
						addRolesGrid.setTitle("为人员"+current_selected_name+"添加角色");
						addRolesGrid.show();
						addRolesGrid.getStore().load({
							params : {
								start : 0,
								limit : pageSize
							}
						});
					},
					scope : this
				}, "-", {
					text : "删除角色",
					handler : function() {
						var sm = roleGrid.getSelectionModel();
						if (sm.hasSelection()) {
							Ext.Msg.confirm('信息', '确定要删除?', function(btn) {
								if (btn == 'yes') {
									var _sr = roleGrid.getSelectionModel()
											.getSelections();
									re_sel_ids = [];
									alert("re_sel_ids length："+re_sel_ids.length);
									for (var i = 0; i < _sr.length; i++) {
										re_sel_ids[i] = _sr[i].get("id");
									}
									Ext.Ajax.request({
										url : "userAction!deleteRoles.action",
										params : {
											selectedRoleList : re_sel_ids,
											current_selected_id : current_selected_id
										}
									});
									/*for (var i = 0; i < _sr.length; i++) {
										// alert(_sr[i].get("id"));
										roleGrid
												.getStore()
												.remove(roleGrid
														.getStore()
														.getAt(_sr[i].get("id")));
									}*/
									//ro_s_store.removeAll();
									ro_s_store.removeAll();
									//roleGrid.show();
									roleGrid.getStore().reload({
										params : {
											start : 0,
											limit : pageSize,
											current_selected_id : current_selected_id
										}
									});
								} else {
									Ext.Msg.alert('信息', "请选中一行！");
								}
							});
						} else {
							Ext.Msg.alert('信息', "请选中纪录！");
						}
					},
					scope : this
				}, "-", {
					text : "人员列表",
					handler : function() {
						roleGrid.hide();
						userGrid.show();
					},
					scope : this
				}],
		enableColumnMove : false,
		selModel : new Ext.grid.CheckboxSelectionModel(),
		bbar : new Ext.PagingToolbar({
					pageSize : pageSize,
					store : ro_s_store
				})
	});
	
	addRolesGrid = new Ext.grid.GridPanel({
		store : ro_l_store,
		cm : ro_cm,
		title : "添加角色",
		autoHeight : true,
		autoWidth : true,
		frame : true,
		stripeRows : true,
		tbar : [{
			text : "添加角色",
			handler : function() {
				var sm = addRolesGrid.getSelectionModel();
				if (sm.hasSelection()) {
					Ext.Msg.confirm('信息', '确定要添加?', function(btn) {
						if (btn == 'yes') {
							var _sr = addRolesGrid.getSelectionModel()
									.getSelections();
									re_sel_ids = [];
							for (var i = 0; i < _sr.length; i++) {
								re_sel_ids[i] = _sr[i].get("id");
							}
							alert("current_selected_id:"+current_selected_id);
							Ext.Ajax.request({
										url : "userAction!addRoles.action",
										params : {
											selectedRoleList : re_sel_ids,
											current_selected_id : current_selected_id
										}
									});
							
							addRolesWin.hide();	
							roleGrid.getStore().removeAll();
							roleGrid.getStore().reload({
										params : {
											start : 0,
											limit : pageSize,
											current_selected_id : current_selected_id
										}
									});
						} else {
							Ext.Msg.alert('信息', "请选中一行！");
						}
					});
				} else {
					Ext.Msg.alert('信息', "请选中纪录！");
				}
			},
			scope : this
		}],
		enableColumnMove : false,
		selModel : new Ext.grid.CheckboxSelectionModel(),
		bbar : new Ext.PagingToolbar({
					pageSize : pageSize,
					store : ro_l_store
				})
	});

	addRolesWin = new Ext.Window({
				layout : 'fit',
				width : 330,
				height : 180,
				closeAction : 'hide',
				modal : true,
				plain : true,
				autoHeight : true,
				autoWidth : true,
				items : [addRolesGrid]
			});
	
	// userGrid.show();
	// addUserWin.show();
	userGrid.getStore().load({
				params : {
					start : 0,
					limit : pageSize
				}
			});
	ro_s_store.on('beforeload', function() {
								Ext.apply(this.baseParams, {
									current_selected_id : current_selected_id
								});
							});
	roleGrid.hide();
	addRolesGrid.hide();		
			
});
